package com.hoshiicloud.user.service.impl.partners;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.UidGenerate4C;
import com.hoshiicloud.user.entity.company.Member;
import com.hoshiicloud.user.entity.partners.StorePartners;
import com.hoshiicloud.user.entity.store.PlatStore;
import com.hoshiicloud.user.entity.store.StoreDepartment;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.partners.StorePartnersMapper;
import com.hoshiicloud.user.service.partners.StorePartnersService;
import com.hoshiicloud.user.service.rbac.IMemberService;
import com.hoshiicloud.user.service.store.PlatStoreService;
import com.hoshiicloud.user.service.store.StoreDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @Author:campchen
 * @Date:Created in 上午 10:05 2019/7/22
 * @PACKAGENAME com.hoshiibuy.partners.service.impl
 * @Description
 */
@Service
public class StorePartnersServiceImpl extends ServiceImpl<StorePartnersMapper, StorePartners> implements StorePartnersService {
    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private PlatStoreService platStoreService;

    @Autowired
    private StoreDepartmentService storeDepartmentService;

    @Autowired
    private IMemberService memberService;

    @Logable(authName = "合作伙伴信息-店铺合作伙伴表管理-根据id查询合作伙伴表")
    @Cacheable(cacheNames = "StorePartners", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Override
    public StorePartners getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Cacheable(cacheNames = "StorePartners", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#orgcode")
    @Logable(authName = "合作伙伴信息-租户合作伙伴表管理 -根据编码查询合作伙伴表 ")
    @Override
    public StorePartners getByOrgcode(String orgcode) {
        Wrapper<StorePartners> wrapper = Wrappers.<StorePartners>query().lambda().eq(StorePartners::getOrgcode, orgcode);
        return baseMapper.selectOne(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StorePartners", allEntries = true)
    @Override
    public String insert(StorePartners entity) {
        String id = idGeneratorService.queryGeneratorId();
        StringBuffer errors = new StringBuffer("新增失败");
        if (id == null || "".equals(id)) {
            errors.append(" id生成有误");
        }
        PlatStore platStore = platStoreService.getById(entity.getStoreid());
        if (platStore == null) {
            errors.append(" 店铺信息有误");
        }
        StoreDepartment storeDepartment = storeDepartmentService.getById(entity.getDepartmentId());
        if (storeDepartment == null) {
            errors.append(" 店铺部门信息有误");
        }
        Member member = memberService.getById(entity.getMemberid());
        if (member == null) {
            errors.append(" 会员信息有误");
        }
        /**生成租户内唯一合作伙伴编码 */
        /**判断编码是否可用*/
        String orgcode = null;
        Boolean flag = true;
        int num = 1;
        /**生成7位编码*/
        UidGenerate4C idWorker = new UidGenerate4C(num);
        while (flag) {
            num++;
            orgcode = String.valueOf(idWorker.getNextId()).substring(10, 17);
            StorePartners storePartners = getByOrgcode(orgcode);
            /**当表中无此编码时，退出循环*/
            if (storePartners == null || "".equals(storePartners)) {
                flag = false;
            }
            /**强制结束条件：重复生成1000次抛异常,退出循环*/
            if (num > 1000) {
                errors.append(" 编码生成有误");
                flag = false;
            }
        }
        /**统一抛异常，将所有异常一起抛出，提升用户体验*/
        if (!"新增失败".equals(errors.toString())) {
            throw new ServiceException(CommonError.error(errors.toString()));
        }
        /**生成编码规则 合作伙伴6+归属层级3+7位随机数*/
        entity.setOrgcode(6 + 3 + orgcode);
        entity.setCreatedtime(LocalDateTime.now());
        entity.setId(Long.parseLong(id));
        entity.setStatus(0);
        entity.setAvailableBalance(new BigDecimal(0));
        entity.setAccountBalance(new BigDecimal(0));
        entity.setFreezingAmount(new BigDecimal(0));
        Integer row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return id;
    }


    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StorePartners", allEntries = true)
    @Override
    public boolean updateById(StorePartners entity) {
        entity.setModifiedtime(LocalDateTime.now());
        Integer row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("跟新失败"));
        }
        return true;
    }

    @Logable(authName = "合作伙伴信息-店铺合作伙伴表管理-分页查询合作伙伴表")
    @Cacheable(cacheNames = "StorePartners", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Override
    public Response getPage(IPage<StorePartners> page, Wrapper<StorePartners> queryWrapper, String key) {
        IPage<StorePartners> StorePartnersIPage = baseMapper.selectPage(page, queryWrapper);
        return Response.data(StorePartnersIPage);
    }
}
